<template>
	<view class="person-select">
    <Card title="人员邀请">
      <template #title>
        <t-button size="extra-small" theme="light" @click="onQuickSearch('（管控岗）')">基础管控岗</t-button>
        <t-button size="extra-small" theme="light" @click="onQuickSearch('（服务岗）')">基础服务岗</t-button>
      </template>
      <!-- <t-button size="extra-small" theme="primary" variant="outline" @click="log">打印</t-button> -->
      <t-search v-model="searchValue" :clearable="false" shape="round" placeholder="搜索姓名或警号" :onSearch="onSearch"></t-search>
      <view class="tree-nav">
        <template v-for="item in navList" :key="item.value" >
          <t-button size="extra-small" theme="primary" variant="outline" @click="onNavLevel(item)">{{ item.label }}</t-button>
          <t-icon class="tree-nav-icon" name="chevron-right-s" size="28" />
        </template>
      </view>
        <!-- v-model="selectList"  @change="onCheckChange(item)" -->
      <t-checkbox-group v-model="selectList" class="tree-children">
        <template v-for="item in children" :key="item.value">
          <t-cell v-if="!disabledChild(item)" :title="item.label" @click="onNextLevel(item)" arrow></t-cell>
          <t-checkbox v-else :value="JSON.stringify(item)" :label="item.label" placement="right" icon="line" />
        </template>
      </t-checkbox-group>
    </Card>
    <t-badge :count="selectList.length">
      <t-fab :icon="iconRender" @click="showTreeSelectPopup = true" :style="checkSelectBtnStyle" />
    </t-badge>
    <t-popup v-model="showTreeSelectPopup" placement="bottom" closeBtn style="height: 258px">
      <PersonList :propList="parseSelectList" title="已选择人员" mode="personSelect" @onDelete="onDeletePerson" />
    </t-popup>
	</view>
</template>

<script setup>
	import { ref, defineProps, onMounted, computed, h } from "vue"
  import { Message } from 'tdesign-mobile-vue';
  import Card from '@/components/Card'
  import PersonList from "@/components/PersonList"
  import { UserCheckedIcon } from 'tdesign-icons-vue-next';
	
  const iconRender = () => h(UserCheckedIcon, { size: '24px' });
  const checkSelectBtnStyle = 'right: 30px; bottom: 95px;'
	const props = defineProps({
		currItem: {},
		personType: 'creator',
    singleSelect: {
      type: Boolean,
      default: false
    }
	})
	
	onMounted(() => {
		getTreeData();
    navList.value = treeData.value.length ? [{ ...treeData.value[0] }] : [];
	})
	
  const searchValue = ref('');
  const navList = ref([]);
  const treeData = ref([]);
  const treeDataBak = ref([]);
  const selectList = ref([]);
  const showTreeSelectPopup = ref(false);
  const children = computed(() => {
    const lastItem = navList.value[navList.value.length - 1];
    if (!navList.value.length || !Array.isArray(lastItem.children)) return [];
    return lastItem.children;
  });
  const disabledChild = computed(() => item => {
    return !Array.isArray(item.children) || !item.children.length;
  })
  const parseSelectList = computed(() => {
    return selectList.value.map(item => JSON.parse(item));
  })

	const log = () => {
		console.log('selectList', selectList.value);
	}

  const onCheckSelect = () => {

  }

  // const onCheckChange = (item) => {
  //   const isSelected = selectList.value.find(it => it.value == item.value);
  //   if (props.singleSelect) {
  //     selectList.value = [item];
  //   }

  //   if () {
  //     selectList.value = selectList.value.filter(it => it.value != item.value);
  //   }
  //   selectList.push(item);
  //   console.log('asd46a5s4', item );
  // }

  const onSearch = value => {
		Message['success']({ offset: [10, 16], content: '搜索成功', icon: true });
	}

  const onNavLevel = item => {
    if (item.value == navList.value[navList.value.length - 1].value) return;
		navList.value.splice(navList.value.findIndex(it => it.value == item.value) + 1);
	}

  const onNextLevel = item => {
    console.log('onNextLevel');
    if (disabledChild.value(item)) return;
		navList.value.push({ ...item });
	}

  const onDeletePerson = item => {
    selectList.value = selectList.value.filter(it => JSON.parse(it).value != item.value);
  }

  const onQuickSearch = keyword => {
    const result = filterTreeByKeyword(treeDataBak.value, keyword);
    treeData.value = result;
    navList.value = treeData.value.length ? [{ ...treeData.value[0] }] : [];
    // console.log('searchTree', result);
    // if (treeData.value.length) navList.value = result[0];
  };

const filterTreeByKeyword = (treeData, keyword) => {
  const processNode = (node) => {
    // 处理子节点，递归过滤
    let filteredChildren = [];
    if (node.children && node.children.length > 0) {
      filteredChildren = node.children.map(child => processNode(child)).filter(child => child !== null);
    }
    // 判断当前节点是否需要保留：自身匹配或子节点有保留
    const isSelfMatched = node.label.includes(keyword);
    const shouldKeep = isSelfMatched || filteredChildren.length > 0;
    if (shouldKeep) {
      // 返回新节点，保留结构，同时处理后的children
      return {
        ...node,
        children: filteredChildren
      };
    } else {
      return null; // 不保留该节点
    }
  };

  // 处理整个树数据，过滤掉null节点
  return treeData.map(node => processNode(node)).filter(node => node !== null);
};
	
	const getTreeData = () => {
		treeDataBak.value = [
			{
				label: '江北区分局',
				value: '500105',
				children: [
					{
						label: '基础管控中心',
						value: '5001051',
						children: [
							{
								label: '张俊（管控岗）',
								value: '302100',
                mjjh: '302100', mjmc: '张俊', zzmc: '基础管控中心', mjlxdh: '17356686812'
							}
						]
					},
					{
						label: '派出所',
						value: '5001052',
						children: [
							{
								label: '江北城派出所',
								value: '500105001',
								children: [
                  {
                    label: '下级部门',
										value: '5001050012',
                    children: [
                      {
                        label: '婷婷（管控岗）',
                        value: '3021135',
                        mjjh: '3021135', mjmc: '婷婷', zzmc: '下级部门', mjlxdh: '17356686812'
                      },
                      {
                        label: '倩倩（服务岗）',
                        value: '3021136',
                        mjjh: '3021136', mjmc: '倩倩', zzmc: '下级部门', mjlxdh: '17356686812'
                      }
                    ]
                  },
									{
										label: '张倩（管控岗）',
										value: '302111',
                    mjjh: '302111', mjmc: '张倩', zzmc: '江北城派出所', mjlxdh: '17356686812'
									},
									{
										label: '陶璇（服务岗）',
										value: '302112',
                    mjjh: '302112', mjmc: '陶璇', zzmc: '江北城派出所', mjlxdh: '17356686812'
									}
								]
							},
							{
								label: '观音桥派出所',
								value: '500105002',
								children: [
									{
										label: '钟鹏',
										value: '302113',
                    mjjh: '302113', mjmc: '钟鹏', zzmc: '观音桥派出所', mjlxdh: '17356686812'
									},
                  {
										label: '欣欣（管控岗）',
										value: '302114',
                    mjjh: '302114', mjmc: '欣欣', zzmc: '观音桥派出所', mjlxdh: '17356686812'
									}
								]
							}
						]
					}
				]
			}
		]
    treeData.value = [...treeDataBak.value]
		// console.log('treeData.value', treeData.value);
	}
	
	const onTreeChange = (item) => {
		console.log('onTreeChange', item, selectList);
		
	}
</script>

<style lang="scss" scoped>
.person-select {
	.tree-nav {
    display: flex;
    flex-wrap: wrap;
    row-gap: 12px;
    align-items: center;
    padding: 12px;
    padding-top: 24px;

    &-icon {
      color: var(--td-brand-color);
    }
  }

  .t-cell {
    padding: 12px;
  }

  .t-badge {
    position: fixed;
    bottom: 145px;
    right: 30px;
  }
}
</style>